<template>
  <div class="chat-page">

    <!-- 科技背景 -->
    <div class="tech-bg">
      <div class="grid-line"></div>
      <div class="tech-lights"></div>
    </div>

    <CharacterHeader :character="currentCharacter" :status="connectionStatus" @go-back="goBack" />

    <div class="chat-container">
      <ChatMessages :messages="messages" :character="currentCharacter" @replay-audio="replayAudio" />

      <ControlPanel :canStart="canStart" :canStop="canStop" :canInterrupt="canInterrupt" :isConnected="isConnected"
        :state="connectionState" :statusText="statusText" :currentRecognition="currentRecognition"
        @start="startConversation" @stop="stopConversation" @interrupt="interruptSpeech" />
    </div>

    <!-- 录音指示器 -->
    <RecordingIndicator :isRecording="isListening && !isAudioPlaying" />

    <!-- 音频播放状态指示器 -->
    <div v-if="isAudioPlaying" class="audio-status-indicator">
      <i class="fas fa-volume-up"></i>
      <span>AI正在说话，请等待...</span>
      <div class="audio-queue-info">
        <span v-if="audioQueue.length > 0">队列中还有 {{ audioQueue.length }} 段音频</span>
      </div>
      <button @click="forceStopAudio" class="stop-audio-btn">
        <i class="fas fa-stop"></i> 停止播放
      </button>
    </div>

    <!-- 调试面板  -->
    <div class="debug-panel" v-if="showDebug">
      <h4>调试信息</h4>
      <p>连接状态: {{ connectionState }}</p>
      <p>WebSocket状态: {{ ws ? ws.readyState : 'null' }}</p>
      <p>语音识别状态: {{ recognition ? 'active' : 'inactive' }}</p>
      <p>当前音频: {{ currentAudio ? 'playing' : 'none' }}</p>
      <p>音频播放中: {{ isAudioPlaying }}</p>
      <p>识别暂停: {{ recognitionPaused }}</p>
      <p>音频队列: {{ audioQueue.length }} 个</p>
      <p>当前消息ID: {{ currentPlayingMessageId }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import CharacterHeader from '@/components/chat/CharacterHeader.vue';
import ChatMessages from '@/components/chat/ChatMessages.vue';
import ControlPanel from '@/components/chat/ControlPanel.vue';
import RecordingIndicator from '@/components/chat/RecordingIndicator.vue';
import { useRoute } from 'vue-router';

const route = useRoute();

// WebSocket相关状态
const ws = ref(null);
const isConnected = ref(false);
const currentRecognition = ref('');
const connectionState = ref('disconnected');
const messages = ref([]);

// 音频播放控制 
const isAudioPlaying = ref(false);
const recognitionPaused = ref(false);
const audioQueue = ref([]); // 音频队列，存储待播放的音频段
const currentPlayingMessageId = ref(null); // 当前播放的消息ID
const messageAudioMap = ref(new Map()); // 消息ID到音频数据的映射

// 调试开关
const showDebug = ref(process.env.NODE_ENV === 'development');

// 语音识别相关的
let recognition = null;
let currentAudio = null;
const userId = 'user_' + Date.now();

let isRecognitionRestarting = ref(false);

// 当前角色分配
const currentCharacter = reactive({
  id: 'harry_potter',
  name: '哈利·波特',
  icon: 'fas fa-magic',
  greeting: '你好！我是哈利·波特，霍格沃茨的学生。'
});

// 角色映射数据
const characterMap = {
  'harry_potter': {
    id: 'harry_potter',
    name: '哈利·波特',
    icon: 'fas fa-magic',
    greeting: '你好！我是哈利·波特，霍格沃茨的学生。很高兴认识你！'
  },
  'socrates': {
    id: 'socrates',
    name: '苏格拉底',
    icon: 'fas fa-brain',
    greeting: '你好，我是苏格拉底。让我们一起探讨生活中的智慧吧。'
  },
  'albert_einstein': {
    id: 'albert_einstein',
    name: '爱因斯坦',
    icon: 'fas fa-atom',
    greeting: '你好！我是爱因斯坦，让我们一起探索科学的奥秘。'
  }
};

// 初始化角色信息的函数
const initializeCharacter = () => {
  const characterId = route.query.characterId || 'harry_potter';
  const characterName = route.query.characterName;

  console.log('URL参数 - characterId:', characterId, 'characterName:', characterName);

  if (characterMap[characterId]) {
    Object.assign(currentCharacter, characterMap[characterId]);
  } else {
    currentCharacter.id = characterId;
    currentCharacter.name = characterName || characterId;
    currentCharacter.icon = 'fas fa-user';
    currentCharacter.greeting = `你好！我是${currentCharacter.name}，很高兴与你对话。`;
  }

  console.log('初始化后的角色信息:', currentCharacter);
};

// 按钮状态控制逻辑
const canStart = computed(() => {
  return connectionState.value === 'disconnected' && !isConnected.value;
});

const canStop = computed(() => {
  return isConnected.value && connectionState.value !== 'disconnected';
});

const canInterrupt = computed(() => {
  return isConnected.value && (connectionState.value === 'speaking' || connectionState.value === 'processing' || isAudioPlaying.value);
});

const isListening = computed(() => connectionState.value === 'listening' && !isAudioPlaying.value);

const connectionStatus = computed(() => {
  if (isAudioPlaying.value) return 'AI正在说话...';
  switch (connectionState.value) {
    case 'connecting': return '连接中...';
    case 'connected': return '已连接';
    case 'listening': return '正在听取语音...';
    case 'processing': return 'AI思考中...';
    case 'speaking': return 'AI回复中...';
    default: return '未连接';
  }
});

const statusText = computed(() => {
  if (isAudioPlaying.value) return 'AI正在说话，请等待播放完成...';
  if (connectionState.value === 'listening' && recognitionPaused.value) {
    return '语音播放完成，即将开始听取您的语音...';
  }
  switch (connectionState.value) {
    case 'connecting': return '正在连接服务器...';
    case 'connected': return '准备就绪，可以开始对话';
    case 'listening': return '正在听取您的语音，请说话...';
    case 'processing': return 'AI正在思考回复...';
    case 'speaking': return 'AI正在回复...';
    default: return '点击开始对话按钮连接';
  }
});

// 添加消息到聊天记录 
const addMessage = (role, content, options = {}) => {
  const message = {
    role,
    content,
    timestamp: new Date(),
    isPlaying: false,
    hasAudio: false,
    audioSegments: [], // 存储音频段
    messageId: Date.now() + Math.random(),
    ...options
  };
  messages.value.push(message);

  // 自动滚动到底部
  setTimeout(() => {
    const area = document.querySelector('.messages-area');
    if (area) area.scrollTop = area.scrollHeight;
  }, 100);

  return message;
};

// 暂停语音识别
const pauseSpeechRecognition = () => {
  console.log('暂停语音识别');
  if (recognition && !recognitionPaused.value) {
    try {
      recognition.stop();
      recognitionPaused.value = true;
      console.log('语音识别已暂停');
    } catch (e) {
      console.log('暂停语音识别出错:', e);
    }
  }
};

// 恢复语音识别
const resumeSpeechRecognition = () => {
  console.log('恢复语音识别');
  if (recognitionPaused.value && isConnected.value && !isAudioPlaying.value) {
    recognitionPaused.value = false;
    setTimeout(() => {
      startSpeechRecognition();
    }, 1500);
  }
};

// 音频队列管理 
const addToAudioQueue = (audioData, messageId, isLastSegment = false) => {
  console.log(`添加音频段到队列，消息ID: ${messageId}, 是否最后一段: ${isLastSegment}`);

  audioQueue.value.push({
    audioData,
    messageId,
    isLastSegment,
    timestamp: Date.now()
  });

  // 如果当前没有播放音频，立即开始播放
  if (!isAudioPlaying.value && audioQueue.value.length > 0) {
    playNextAudioFromQueue();
  }
};

// 从队列播放下一个音频段
const playNextAudioFromQueue = async () => {
  if (audioQueue.value.length === 0) {
    console.log('音频队列为空，播放结束');
    isAudioPlaying.value = false;
    currentPlayingMessageId.value = null;

    // 更新消息播放状态
    const playingMessage = messages.value.find(msg => msg.isPlaying);
    if (playingMessage) {
      playingMessage.isPlaying = false;
    }

    connectionState.value = 'listening';
    updatePlaybackStatus('stopped');
    // resumeSpeechRecognition();
    return;
  }

  const audioItem = audioQueue.value.shift();
  console.log(`开始播放音频段，消息ID: ${audioItem.messageId}`);

  try {
    // 暂停语音识别（如果还没暂停）
    if (!recognitionPaused.value) {
      pauseSpeechRecognition();
    }

    isAudioPlaying.value = true;
    currentPlayingMessageId.value = audioItem.messageId;
    connectionState.value = 'speaking';

    // 更新消息播放状态
    const targetMessage = messages.value.find(msg => msg.messageId === audioItem.messageId);
    if (targetMessage) {
      targetMessage.isPlaying = true;
    }

    let audioBlob;
    if (audioItem.audioData instanceof Blob) {
      audioBlob = audioItem.audioData;
    } else if (typeof audioItem.audioData === 'string') {
      audioBlob = base64ToBlob(audioItem.audioData, 'audio/wav');
    } else {
      throw new Error('不支持的音频数据格式');
    }

    const audioUrl = URL.createObjectURL(audioBlob);
    currentAudio = new Audio(audioUrl);

    // 保存音频数据到消息对象（用于重播）
    if (targetMessage) {
      if (!targetMessage.audioSegments) {
        targetMessage.audioSegments = [];
      }
      targetMessage.audioSegments.push(audioItem.audioData);
      targetMessage.hasAudio = true;
    }

    // 音频播放完成
    currentAudio.onended = () => {
      console.log(`音频段播放完成，消息ID: ${audioItem.messageId}`);
      currentAudio = null;
      URL.revokeObjectURL(audioUrl);

      // 如果这是最后一段音频且队列中没有同一消息的其他段，则结束播放
      const hasSameMessageInQueue = audioQueue.value.some(item => item.messageId === audioItem.messageId);

      if (audioItem.isLastSegment || !hasSameMessageInQueue) {
        console.log(`消息 ${audioItem.messageId} 的所有音频段播放完成`);
        // 如果队列中还有其他消息的音频，继续播放
        if (audioQueue.value.length > 0) {
          playNextAudioFromQueue();
        } else {
          // 所有音频播放完成
          isAudioPlaying.value = false;
          currentPlayingMessageId.value = null;

          if (targetMessage) {
            targetMessage.isPlaying = false;
          }

          connectionState.value = 'listening';
          updatePlaybackStatus('stopped');
          setTimeout(() => {
            if (isConnected.value && !recognitionPaused.value) {
              resumeSpeechRecognition();
            }
          }, 2000); // 延迟2秒再启动语音识别
        }
      } else {
        // 继续播放下一段
        playNextAudioFromQueue();
      }
    };

    // 音频播放错误
    currentAudio.onerror = (error) => {
      console.error('音频播放失败:', error);
      currentAudio = null;
      URL.revokeObjectURL(audioUrl);

      if (targetMessage) {
        targetMessage.isPlaying = false;
      }

      // 继续播放队列中的下一个音频
      playNextAudioFromQueue();
    };

    updatePlaybackStatus('playing', audioQueue.value.length);
    await currentAudio.play();

  } catch (error) {
    console.error('播放音频段失败:', error);
    // 继续播放队列中的下一个音频
    playNextAudioFromQueue();
  }
};

// 强制停止音频播放 
const forceStopAudio = () => {
  console.log('强制停止所有音频播放');

  // 清空音频队列
  audioQueue.value = [];

  // 停止当前播放
  if (currentAudio) {
    currentAudio.pause();
    currentAudio.currentTime = 0;
    currentAudio = null;
  }

  // 停止所有正在播放的消息
  messages.value.forEach(msg => {
    if (msg.isPlaying) {
      msg.isPlaying = false;
    }
  });

  isAudioPlaying.value = false;
  currentPlayingMessageId.value = null;
  connectionState.value = 'listening';

  // 发送停止播放状态给后端
  updatePlaybackStatus('stopped', 0);

  // 恢复语音识别
  // resumeSpeechRecognition();

  addMessage('system', '已停止AI语音播放');
};

// 重播音频功能 - 增强版支持多段音频
const replayAudio = (messageId) => {
  const message = messages.value.find(msg => msg.messageId === messageId);
  if (message && message.audioSegments && message.audioSegments.length > 0) {
    console.log(`重播音频，消息ID: ${messageId}, 音频段数: ${message.audioSegments.length}`);

    // 先停止当前播放
    if (currentAudio || isAudioPlaying.value) {
      forceStopAudio();
    }

    // 将所有音频段添加到队列
    message.audioSegments.forEach((audioData, index) => {
      const isLast = index === message.audioSegments.length - 1;
      addToAudioQueue(audioData, messageId, isLast);
    });
  }
};

// 开始对话
const startConversation = async () => {
  try {
    connectionState.value = 'connecting';
    addMessage('system', '正在连接服务器...');

    const wsUrl = `ws://localhost:8001/ws?user_id=${userId}`;
    console.log('正在连接WebSocket:', wsUrl);
    ws.value = new WebSocket(wsUrl);

    ws.value.onopen = () => {
      console.log('WebSocket连接成功');
      connectionState.value = 'connected';
      isConnected.value = true;
      addMessage('system', '连接成功！');

      // 发送角色切换消息
      console.log('发送角色切换消息:', currentCharacter.id);
      ws.value.send(JSON.stringify({
        type: 'character_change',
        character_id: currentCharacter.id
      }));

      // 添加角色问候语
      addMessage('assistant', currentCharacter.greeting);

      // 启动语音识别
      startSpeechRecognition();
    };

    ws.value.onmessage = (event) => {
      try {
        if (event.data instanceof Blob) {
          console.log('收到二进制音频数据');
          handleAudioBlob(event.data);
        } else {
          const data = JSON.parse(event.data);
          handleWebSocketMessage(data);
        }
      } catch (err) {
        console.error('处理WebSocket消息失败:', err, event.data);
      }
    };

    ws.value.onclose = (event) => {
      console.log('WebSocket连接关闭:', event.code, event.reason);
      connectionState.value = 'disconnected';
      isConnected.value = false;
      stopSpeechRecognition();
      forceStopAudio(); // 确保停止所有音频播放
      addMessage('system', '连接已断开');
    };

    ws.value.onerror = (error) => {
      console.error('WebSocket错误:', error);
      connectionState.value = 'disconnected';
      isConnected.value = false;
      addMessage('system', '连接失败，请检查服务器状态');
    };

  } catch (error) {
    console.error('连接失败:', error);
    connectionState.value = 'disconnected';
    addMessage('system', '连接失败：' + error.message);
  }
};

// 处理音频Blob数据 - 支持流式音频
const handleAudioBlob = async (audioBlob) => {
  try {
    console.log('处理音频Blob数据');

    // 为当前对话创建一个消息（如果还没有正在播放的消息）
    let targetMessage = messages.value.find(msg => msg.messageId === currentPlayingMessageId.value);

    if (!targetMessage) {
      targetMessage = addMessage('assistant', '正在播放语音回复...', {
        hasAudio: true,
        audioSegments: []
      });
    }

    // 添加到音频队列
    addToAudioQueue(audioBlob, targetMessage.messageId, false);

  } catch (error) {
    console.error('处理音频数据失败:', error);
  }
};

const handleWebSocketMessage = (data) => {
  console.log('收到WebSocket消息:', data);

  switch (data.type) {
    case 'character_changed':
      console.log('角色切换成功:', data.character_id);
      addMessage('system', `已切换到角色: ${currentCharacter.name}`);
      break;

    case 'message_received':
      console.log('消息已接收:', data.content);
      break;

    case 'update_dialogue':
      handleAIResponse(data);
      break;

    case 'audio_data':
      if (data.audio) {
        handleBase64Audio(data.audio);
      }
      break;

    case 'text_response':
      addMessage('assistant', data.text);
      // if (!isAudioPlaying.value) {
      //   connectionState.value = 'listening';
      //   if (!recognition) {
      //     setTimeout(() => startSpeechRecognition(), 500);
      //   }
      // }
      break;

    case 'audio_chunk':
      if (data.audio_data) {
        handleAudioChunk(data.audio_data);
      }
      break;

    case 'speech_response':
      handleSpeechResponse(data);
      break;

    case 'audio_end':
      // 音频流结束标记
      handleAudioStreamEnd(data);
      break;

    default:
      console.log('未知消息类型:', data);
  }
};

// 处理Base64音频数据 - 支持流式
const handleBase64Audio = async (base64Audio, isLastSegment = false) => {
  try {
    console.log('处理Base64音频数据');

    let targetMessage = messages.value.find(msg => msg.messageId === currentPlayingMessageId.value);

    if (!targetMessage) {
      targetMessage = addMessage('assistant', '收到语音回复', {
        hasAudio: true,
        audioSegments: []
      });
    }

    // 添加到音频队列
    addToAudioQueue(base64Audio, targetMessage.messageId, isLastSegment);

  } catch (error) {
    console.error('处理Base64音频失败:', error);
  }
};

// 处理音频片段 
const handleAudioChunk = async (audioData) => {
  console.log('收到音频片段');
  await handleBase64Audio(audioData, false);
};

// 处理音频流结束
const handleAudioStreamEnd = (data) => {
  console.log('音频流结束', data);

  // 如果有消息ID，标记该消息的最后一个音频段
  if (data.message_id) {
    const lastAudioInQueue = audioQueue.value
      .filter(item => item.messageId === data.message_id)
      .pop();

    if (lastAudioInQueue) {
      lastAudioInQueue.isLastSegment = true;
    }
  }
};

// 处理语音回复
const handleSpeechResponse = async (data) => {
  const messageText = data.text || '收到语音回复';
  const targetMessage = addMessage('assistant', messageText, {
    hasAudio: !!(data.audio_url || data.audio),
    audioSegments: []
  });

  if (data.audio_url) {
    try {
      const response = await fetch(data.audio_url);
      const audioBlob = await response.blob();
      addToAudioQueue(audioBlob, targetMessage.messageId, true);
    } catch (error) {
      console.error('播放语音回复失败:', error);
    }
  } else if (data.audio) {
    addToAudioQueue(data.audio, targetMessage.messageId, true);
  }
};

// AI回复处理 
const handleAIResponse = async (data) => {
  connectionState.value = 'speaking';

  const messagesArray = data.data || [];
  for (const msg of messagesArray) {
    if (msg.role === 'assistant') {
      const messageText = msg.content || '收到回复';
      const aiMessage = addMessage('assistant', messageText, {
        hasAudio: !!(msg.audio_url || msg.audio),
        audioSegments: []
      });

      if (msg.audio_url) {
        try {
          const response = await fetch(msg.audio_url);
          const audioBlob = await response.blob();
          addToAudioQueue(audioBlob, aiMessage.messageId, true);
        } catch (error) {
          console.error('播放AI语音失败:', error);
        }
      } else if (msg.audio) {
        addToAudioQueue(msg.audio, aiMessage.messageId, true);
      } else {
        if (!isAudioPlaying.value) {
          connectionState.value = 'listening';
          // 
        }
      }
    }
  }
};

// base64转Blob函数
const base64ToBlob = (base64, mimeType) => {
  const byteCharacters = atob(base64);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type: mimeType });
};

// 语音识别启动逻辑
const startSpeechRecognition = () => {
  if (isAudioPlaying.value) {
    console.log('音频播放中，跳过语音识别启动');
    return;
  }

  if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
    addMessage('system', '您的浏览器不支持语音识别功能');
    return;
  }

  if (recognition) {
    try {
      recognition.stop();
    } catch (e) {
      console.log('停止旧的语音识别实例:', e);
    }
  }

  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  recognition = new SpeechRecognition();
  recognition.continuous = true;
  recognition.interimResults = true;
  recognition.lang = 'zh-CN';

  recognition.onstart = () => {
    console.log('语音识别开始');
    if (connectionState.value === 'connected') {
      connectionState.value = 'listening';
    }
    isRecognitionRestarting.value = false;
    recognitionPaused.value = false;
  };

  recognition.onresult = (event) => {
    if (isAudioPlaying.value) {
      console.log('音频播放中，忽略语音识别结果');
      return;
    }

    let finalTranscript = '';
    let interimTranscript = '';

    for (let i = event.resultIndex; i < event.results.length; i++) {
      const transcript = event.results[i][0].transcript;
      if (event.results[i].isFinal) {
        finalTranscript += transcript;
      } else {
        interimTranscript += transcript;
      }
    }

    currentRecognition.value = interimTranscript;

    if (finalTranscript.trim()) {
      sendUserMessage(finalTranscript.trim());
      currentRecognition.value = '';
    }
  };

  recognition.onerror = (event) => {
    console.error('语音识别错误:', event.error);
    if (event.error === 'not-allowed') {
      addMessage('system', '请允许麦克风权限以使用语音功能');
    } else if (event.error === 'no-speech') {
      console.log('未检测到语音');
    } else {
      console.log(`语音识别错误: ${event.error}`);
    }
    isRecognitionRestarting.value = false;
  };

  recognition.onend = () => {
    console.log('语音识别结束');

    if (isConnected.value &&
      !isRecognitionRestarting.value &&
      !isAudioPlaying.value &&
      !recognitionPaused.value &&
      (connectionState.value === 'listening' || connectionState.value === 'connected')) {

      isRecognitionRestarting.value = true;
      setTimeout(() => {
        if (isConnected.value && !isAudioPlaying.value && !recognitionPaused.value) {
          try {
            startSpeechRecognition();
            console.log('重启语音识别成功');
          } catch (e) {
            console.log('重启语音识别失败:', e);
            isRecognitionRestarting.value = false;
          }
        } else {
          isRecognitionRestarting.value = false;
        }
      }, 1000);
    }
  };

  try {
    recognition.start();
    console.log('启动语音识别成功');
  } catch (e) {
    console.error('启动语音识别失败:', e);
    addMessage('system', '启动语音识别失败');
    isRecognitionRestarting.value = false;
  }
};

// 发送用户消息函数
const sendUserMessage = (text) => {
  console.log('发送用户消息:', text);

  addMessage('user', text);

  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send(JSON.stringify({
      type: 'message',
      content: text
    }));

    connectionState.value = 'processing';
  } else {
    console.error('WebSocket连接状态异常:', ws.value?.readyState);
    addMessage('system', '连接已断开，无法发送消息');
  }
};

// 更新播放状态
const updatePlaybackStatus = (status, queueSize = 0) => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send(JSON.stringify({
      type: 'playback_status',
      status: status,
      queue_size: queueSize
    }));
  }
};

// 停止对话
const stopConversation = () => {
  console.log('停止对话');

  stopSpeechRecognition();
  forceStopAudio();

  if (ws.value) {
    ws.value.close();
    ws.value = null;
  }

  connectionState.value = 'disconnected';
  isConnected.value = false;
  currentRecognition.value = '';
  isRecognitionRestarting.value = false;
  addMessage('system', '对话已结束');
};

// 打断AI说话
const interruptSpeech = () => {
  console.log('打断AI说话');
  forceStopAudio();
};

// 停止语音识别
const stopSpeechRecognition = () => {
  if (recognition) {
    try {
      recognition.stop();
      console.log('停止语音识别');
    } catch (e) {
      console.log('停止语音识别出错:', e);
    }
    recognition = null;
  }
  isRecognitionRestarting.value = false;
  recognitionPaused.value = false;
};

// 返回上一页
const goBack = () => {
  if (isConnected.value && confirm('对话进行中，确定要离开吗？')) {
    stopConversation();
    window.history.back();
  } else if (!isConnected.value) {
    window.history.back();
  }
};

// 在组件挂载时初始化角色
onMounted(() => {
  console.log('语音聊天页面已加载');
  initializeCharacter();
});

onUnmounted(() => {
  stopConversation();
});
</script>
<style scoped>
.chat-page {
  position: relative;
  min-height: 100vh;
  background: rgba(0, 0, 0, 0);
  color: var(--text-light);
  overflow-x: hidden;
}

/* 科技感背景 */
.tech-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  overflow: hidden;
  background: radial-gradient(circle at center, rgba(74, 108, 247, 0.05) 0%, transparent 80%);
}

.grid-line {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image:
    linear-gradient(rgba(74, 108, 247, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(74, 108, 247, 0.05) 1px, transparent 1px);
  background-size: 40px 40px;
  z-index: 0;
}

.tech-lights {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background:
    radial-gradient(circle at 20% 30%, rgba(74, 108, 247, 0.1) 0%, transparent 20%),
    radial-gradient(circle at 80% 70%, rgba(255, 107, 107, 0.1) 0%, transparent 25%),
    radial-gradient(circle at 40% 80%, rgba(31, 221, 161, 0.1) 0%, transparent 15%);
  z-index: 1;
}

/* 聊天容器 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 80px);
  max-width: 900px;
  margin: 0 auto;
  padding: 0 15px;
  position: relative;
  z-index: 5;
}

/* 音频播放状态指示器 */
.audio-status-indicator {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.9);
  color: #f59e0b;
  padding: 20px;
  border-radius: 15px;
  border: 2px solid #f59e0b;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  z-index: 1000;
  backdrop-filter: blur(10px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
}

.audio-status-indicator i {
  font-size: 1.5rem;
  animation: pulse 1.5s infinite;
}

.stop-audio-btn {
  background: #dc2626;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 5px;
}

.stop-audio-btn:hover {
  background: #b91c1c;
  transform: scale(1.05);
}

/* 调试面板 */
.debug-panel {
  position: fixed;
  bottom: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 10px;
  border-radius: 5px;
  font-size: 12px;
  z-index: 1000;
  max-width: 250px;
}

.debug-panel h4 {
  margin: 0 0 5px 0;
  color: #4a6cf7;
}

.debug-panel p {
  margin: 2px 0;
}
</style>